<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="遇见与成长 - 图腾客户管理系统 - 推广绩效">
    <title>{{title}}</title>
    <link rel="stylesheet" href="/apps/css/bootstrap.min.css">
    <link rel="stylesheet" href="/apps/css/fontawesome-free-6.4.0-web/css/all.css">
    <link rel="stylesheet" href="/apps/css/mui.css">
</head>
<body>
    <header class="d-flex align-items-center bg-custom-color p-3">
        <button id="backButton" class="btn btn-primary rounded-circle me-3" style="background-color: white;" onclick="history.back();">
            <i class="fas fa-arrow-left custom-color"></i>
        </button>
        <span class="title-text text-white fs-5">{{excerpt}}</span>
    </header>
    <div class="container">
        <div class="content">
            <div class="row">
                <div class="col-12">
                    <p>{{{description}}}</p>
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered">
                            <thead class="table-light">
                                <tr>
                                    {{#each fields}}
                                    <th scope="col" class="cell-content">{{this}}</th>
                                    {{/each}}
                                </tr>
                            </thead>
                            <tbody>
                                {{#each rows}}
                                <tr data-id="{{this.id}}" onclick="showClientModal('{{this.rep}} {{@root.view}} {{onset}}');">
                                    {{#each this}}
                                    <td class="cell-content">{{this}}</td>
                                    {{/each}}
                                </tr>
                                {{/each}}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <nav aria-label="Page navigation" class="pagination-container">
            <button id="homeButton" class="btn btn-primary position-absolute top-0 start-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="window.location.href='https://totemlife.cn/apps/crm/';">
                <i class="fas fa-home" style="color:white;"></i>
            </button>
            <button id="formButton" class="btn btn-primary position-absolute top-0 end-0 m-3 rounded-circle" style="width: 50px; height: 50px; padding: 0;" onclick="showQueryForm();">
                <i class="fas fa-search" style="color: white;"></i>
            </button>
            <ul class="pagination">
                {{{paginator}}}
            </ul>
        </nav>
    </div>
    <div class="modal fade" id="menuModal" tabindex="-1" aria-labelledby="menuModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="menuModalTitle">选择应用操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="menuModalBody" style="text-align:center;">
                    <a style="text-decoration: none;" href="https://totemlife.cn/apps/crm/"><h5>ENG应用首页</h5></a>
                    <hr>
                    <a style="text-decoration: none;" href="#" id ="queryPromotions" onclick="showQueryForm();"><h5>筛选推广数据</h5></a>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="clientModal" tabindex="-1" aria-labelledby="clientModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="clientModalTitle">选择操作</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="clientModalBody">
                    <h5>
                        点开这里想要看见什么呢？
                    </h5>
                    <p>
                        快来登记你想要的功能吧 <a href="https://wj.qq.com/s2/12774786/e9bb/">CRM使用反馈</a>
                    </p>
                </div>
                <div class="modal-footer" id="clientModalFooter">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal">关闭弹窗</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="queryModal" tabindex="-1" aria-labelledby="queryModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="queryModalLabel">设置统计参数</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="queryForm" onsubmit="submitQueryForm()">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col">
                                <div class="mb-3">
                                    <label for="begin" class="form-label">起始日期</label>
                                    <input type="date" class="form-control" id="begin" name="begin" value="{{begin}}">
                                </div>
                            </div>
                            <div class="col">
                                <div class="mb-3">
                                    <label for="end" class="form-label">结束日期</label>
                                    <input type="date" class="form-control" id="end" name="end" value="{{end}}">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="view" class="form-label">统计周期</label>
                            <select class="form-select" id="view" name="view">
                                <option value="MONTH">按每月</option>
                                <option value="WEEK">按每周</option>
                                <option value="YEAR">按每年</option>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col">
                                <div class="mb-3">
                                    <label for="rep" class="form-label">代表代码</label>
                                    <input type="text" class="form-control" id="rep" name="rep" value="{{rep}}">
                                </div>
                            </div>
                            <div class="col">
                                <div class="mb-3">
                                    <label for="team" class="form-label">部门代码</label>
                                    <input type="text" class="form-control" id="team" name="team" value="{{team}}">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer" id="clientModalFooter">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭查询</button>
                            <button type="submit" class="btn btn-primary">查询数据</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <footer class="footer" style="text-align: center;">
        <div class="row">
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&nbsp;</div>
            <div class="text-muted">&copy;2023 图腾生命医学</div>
            <div class="text-muted">我们为人类免疫事业而奉献</div>
        </div>
    </footer>
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <script src="/apps/js/bootstrap.bundle.min.js"></script>
    <script src="/apps/js/crm-hbs-utils.js"></script>
    <script src="/apps/js/wx-client-dom.js"></script>
    <script>
        //async function getTargetTip(event, target, params) {} //in crm-hbs-utils.js
        function showMenuModal() {
            const modal = new bootstrap.Modal(document.getElementById('menuModal'));
            modal.show();
        };
        function showClientModal(id) {
            const [rep, view, onset] = id.split(' ');
            console.log('debug 1:', rep, view, onset);
            fetchItemData(rep, view, onset);
        }
        function fetchItemData(rep, view, onset) {
            const queryParams = new URLSearchParams({ rep, view, onset });
            const url = `https://totemlife.cn/apps/crm/get-promotion-data?${queryParams.toString()}`;
            fetch(url)
                .then(response => response.json())
                .then(data => {
                    const { title, excerpt, description, activeClientDataMap, firstOrderClientDataMap } = data;
                    displayPromotionData(title, excerpt, description, activeClientDataMap, firstOrderClientDataMap);
                 })
            .catch(error => console.log(error));
        }

        function displayPromotionData(title, excerpt, description, activeClientDataMap, firstOrderClientDataMap) {
            const modal = new bootstrap.Modal(document.getElementById('clientModal'));
            const modalTitle = document.getElementById('clientModalTitle');
            const modalBody = document.getElementById('clientModalBody');
            modalTitle.textContent = title;
            let allClientIds = new Set([...Object.keys(activeClientDataMap), ...Object.keys(firstOrderClientDataMap)]);
            let combinedDataMap = new Map();
            for(let clientId of allClientIds) {
                let activeClientData = activeClientDataMap[clientId] || { recruitedList: [] };
                let firstOrderClientData = firstOrderClientDataMap[clientId] || { firstOrderList: [] };
                combinedDataMap.set(clientId, {
                    recruitedList: activeClientData.recruitedList,
                    firstOrderList: firstOrderClientData.firstOrderList,
                    mtaRecruitedList: activeClientData.mtaRecruitedList || [],
                    npoUserList: activeClientData.npoUserList || [],
                    qpoUserList: activeClientData.qpoUserList || []
                });
            }
            let combinedTableRows = '';
            for (let [clientId, clientData] of combinedDataMap) {
                let clientIdLink = `<a href="#" onclick="getTargetTip(event, '用户','type=client&id=${clientId}')">${clientId}</a>`;
                let recruitedList = clientData.recruitedList.map(userId => {
                    let specialSignsLeft = '';
                    let specialSignsRight = '';
                    let usingBol
                    if (clientData.mtaRecruitedList.includes(userId)) specialSignsLeft += '^';
                    if (clientData.qpoUserList.includes(userId)) specialSignsRight += '!';
                    let userIdContent = `${specialSignsLeft}${userId}${specialSignsRight}`;
                    if (clientData.npoUserList.includes(userId)) userIdContent = `<strong>${userIdContent}</strong>`;
                    return `<a href="#" onclick="getTargetTip(event, '用户','type=user&id=${userId}')">${userIdContent}</a>`;
                }).join(',');
                let firstOrderList = clientData.firstOrderList.map(orderId => `<a href="#" onclick="getTargetTip(event, '订单','type=order&id=${orderId}')">${orderId}</a>`).join(',');
                combinedTableRows += `
                    <tr>
                        <td>${clientIdLink}</td>
                        <td>${recruitedList}</td>
                        <td>${firstOrderList}</td>
                    </tr>
                `;
            }
            modalBody.innerHTML = `
                <h5>${excerpt}</h5>
                <p>${description}</p>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>CID</th>
                                <th>新荐用户</th>
                                <th>成交首单</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${combinedTableRows}
                    </tbody>
                </table>
                </div>
            `;
            modal.show();
        }

        function showQueryForm() {
            const modal = new bootstrap.Modal(document.getElementById('queryModal'));
            modal.show();
        }
        function submitQueryForm() {
            const queryParams = new URLSearchParams();
            const paramsToCheck = ['view', 'begin', 'end', 'rep', 'team'];
            for (const param of paramsToCheck) {
                const value = document.getElementById(param).value;
                if (value && value !== '') queryParams.append(param, value);
            }
            const url = `https://totemlife.cn/apps/crm/promotions?${queryParams.toString()}`;
            window.location.href = url;
        }
    </script>
</body>
</html>
